<template>
  <AcceptHandleHeadComponent ref="acceptHandleHeadRef" :ucolumns="ucolumns" :needDealNum="needDealNum"
    :type="LableTitle.condeployDone" :needMoreQuery="true" :showCaseNoQuery="false" @myEvent="myEvent"
    @setColumns="setColumns" @onSearch="onSearch" @onReset="reQuery">
    <div slot="headLeft">
      <a-form-item style="display: flex; margin-bottom: 0px">
        <a-input v-model="queryParam.personname" placeholder="请输入申请人" allowClear style="height: 40px" />
      </a-form-item>
    </div>

    <div slot="headRight" style="margin-right: 20px">
      <a-button type="primary" class="btn_normal_color" style="margin-left: 8px" @click="importPhotoZip">导出对象图片</a-button>
      <a-button type="primary" class="btn_primary_color" style="margin-left: 8px" @click="importWord">导出资料名单</a-button>
    </div>

    <!-- 其他查询条件 -->
    <div slot="more">
      <a-form layout="inline" class="accept_more_operate_moreForm">
        <a-collapse v-model="collapseKey" class="accept_more_operate_moreForm_collapse">
          <a-collapse-panel :show-arrow="false" disabled key="1" style="font-weight: bold">
            <div slot="header" class="accept_more_operate_moreForm_collapse_head">
              <a-row :gutter="48" style="width: 100%">
                <a-col @click.stop="() => { }" :md="8" :sm="24">
                  <a-form-item label="罪名：">
                    <a-input v-model="queryParam.crime" placeholder="请输入罪名" allowClear />
                  </a-form-item>
                </a-col>
                <a-col @click.stop="() => { }" :md="8" :sm="24">
                  <a-form-item label="执行地">
                    <a-input v-model="queryParam.exeaddr" placeholder="请输入执行地" allowClear />
                  </a-form-item>
                </a-col>
                <a-col @click.stop="() => { }" :md="8" :sm="24">
                  <a-form-item label="布控编号">
                    <a-input v-model="queryParam.concode" placeholder="请输入布控编号" allowClear />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
            <a-row :gutter="48" style="width: 100%" class="accept_more_operate_moreForm_collapse_body">
              <a-col @click.stop="() => { }" :md="12" :sm="24">
                <a-form-item label="矫正开始时间：">
                  <a-date-picker v-model="queryParam.startdate_01" :style="{ width: 'calc(50% - 10px)' }"
                    placeholder="开始日期" format="YYYY-MM-DD" allowClear @change="startdateListen()" />
                  ~
                  <a-date-picker v-model="queryParam.startdate_02" :style="{ width: 'calc(50% - 12px)' }"
                    placeholder="结束日期" format="YYYY-MM-DD" allowClear @change="startdateListen()" />
                </a-form-item>
              </a-col>
              <a-col @click.stop="() => { }" :md="12" :sm="24">
                <a-form-item label="布控开始时间：">
                  <a-date-picker v-model="queryParam.constartdate" :style="{ width: 'calc(50% - 10px)' }"
                    placeholder="开始日期" format="YYYY-MM-DD" allowClear @change="constartdateListen()" />
                  ~
                  <a-date-picker v-model="queryParam.consenddate" :style="{ width: 'calc(50% - 12px)' }"
                    placeholder="结束日期" format="YYYY-MM-DD" allowClear @change="constartdateListen()" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form>
    </div>

    <template slot="content">
      <div class="accept_content_table">
        <!-- 表格数据 -->
        <a-table :scroll="scroll" :columns="ucolumns" :data-source="listData" :pagination="upagination" :loading="loading"
          rowKey="taskid" @change="tableChange" size="middle" :bordered="ubordered" :rowClassName="rowClassName"
          :components="header" ref="table" :key="tableCountKey" :row-selection="rowSelection">
          <span slot="serial" slot-scope="text, record, index">
            {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
          </span>

          <div slot="personnameSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ record.personname }}</span>
              </template>
              <a @click="showPersonInfo(record)">{{ record.personname }}</a>
            </a-tooltip>
          </div>

          <div slot="crimeSlot" slot-scope="crime" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ crime }}</span>
              </template>
              {{ crime }}
            </a-tooltip>
          </div>

          <div slot="crctypeSlot" slot-scope="crctype" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ crcTypeLabel(crctype) }}</span>
              </template>
              {{ crcTypeLabel(crctype) }}
            </a-tooltip>
          </div>

          <div slot="exeaddrSlot" slot-scope="exeaddr" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ exeaddr }}</span>
              </template>
              {{ exeaddr }}
            </a-tooltip>
          </div>

          <div slot="startdateSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
            <span v-if="record.startdate_bz">{{ record.startdate_bz | getTimeFormat('YYYY年M月D日') }} -
              {{ record.enddate_bz | getTimeFormat('YYYY年M月D日') }}</span>
          </div>

          <div slot="constartdateSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
            <span v-if="record.constartdate">{{ record.constartdate | getTimeFormat('YYYY年M月D日') }} -
              {{ record.conenddate | getTimeFormat('YYYY年M月D日') }}</span>
          </div>

          <div slot="processSlot" slot-scope="process" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ process }}</span>
              </template>
              {{ process }}
            </a-tooltip>
          </div>

          <template slot="operation" slot-scope="text, record">
            <!-- 补正状态的操作 -->
            <a href="javascript:;" @click="showHand(record, '4')">详情</a>
          </template>
        </a-table>
      </div>

      <CrcPersonModal ref="crcPersonModalRef"></CrcPersonModal>
    </template>
  </AcceptHandleHeadComponent>
</template>

<script>
import drag from '@/components/TableDrag/drag'
import { LableTitle } from '@/enumeration/LableTitle.js'
import { queryMf_MyTaskDoneList } from '@/api/workflow/mf_MyTaskDone'
import { APP_USER, APP_DEPT } from '@/store/mutation-types.js'
import storage from 'store'
import AcceptHandleHeadComponent from '@/views/accept/component/AcceptHandleHeadComponent.vue'
import { downloadPersonPhoto, downloadPersonWord } from '@/api/correction/crc_person.js'
import { downloadFile } from '@/utils/util'
import { Tp_biztype } from '@/enumeration/Tp_biztype'
import { Tp_crc_user } from '@/enumeration/correction/Tp_crc_user'
const ucolumns = [
  {
    title: '序号',
    width: 50,
    key: 'index',
    align: 'center',
    fixed: 'left',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '姓名',
    dataIndex: 'personname',
    key: 'personname',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'personnameSlot' }
  },
  {
    title: '罪名',
    dataIndex: 'crime',
    key: 'crime',
    width: 100,
    align: 'left',
    scopedSlots: { customRender: 'crimeSlot' }
  },
  {
    title: '业务名称',
    dataIndex: 'process',
    key: 'process',
    width: 200,
    align: 'center',
    scopedSlots: { customRender: 'processSlot' }
  },
  {
    title: '矫正类型',
    dataIndex: 'crctype',
    key: 'crctype',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'crctypeSlot' }
  },
  {
    title: '矫正时间',
    dataIndex: 'startdate',
    key: 'startdate',
    width: 200,
    align: 'center',
    scopedSlots: { customRender: 'startdateSlot' }
  },
  {
    title: '布控时间',
    dataIndex: 'constartdate',
    key: 'constartdate',
    width: 200,
    align: 'center',
    scopedSlots: { customRender: 'constartdateSlot' }
  },
  {
    title: '布控编号',
    dataIndex: 'concode',
    key: 'concode',
    width: 200,
    align: 'left'
  },
  {
    title: '执行地',
    dataIndex: 'exeaddr',
    key: 'exeaddr',
    width: 200,
    align: 'left',
    scopedSlots: { customRender: 'exeaddrSlot' }
  },
  {
    title: '处理人',
    dataIndex: 'startuserid',
    key: 'startuserid',
    align: 'center',
    width: 150
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 220,
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'operation' }
  }
]

export default {
  data() {
    return {
      applyid: null,
      ucolumns: ucolumns,
      // columns: columns,
      cardColumns: ucolumns,
      needDealNum: undefined,
      Tp_biztype: Tp_biztype,
      Tp_crc_user: Tp_crc_user,
      queryParam: {
        personname: '', // 社矫对象
        crime: '', // 罪名
        exeaddr: '', // 执行地
        concode: '', // 布控编号
        startdate_01: null, // 矫正开始时间
        startdate_02: null, // 矫正结束时间
        constartdate: null, // 布控开始时间
        consenddate: null, // 布控结束时间
        pageNumber: 1,
        pageSize: 20,
        order: 'desc',
        userid: '', // 用户id
        matid: null,
        state: '1'
      },
      listData: [],
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: total => `共计 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100']
      },
      loading: false,
      ubordered: true, // 表格边框是否显示
      mixins: [drag],
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      LableTitle: LableTitle,
      header: undefined,
      tableCountKey: 0,
      collapseKey: [], // 折叠面板key
      rowSelection: {
        type: 'checkbox',
        // 不使用箭头函数就无法获取this
        // 单选
        onSelect: (record, selected, selectedRows, nativeEvent) => {
          // console.log(record, selected, selectedRows, nativeEvent)
          const list = this.rowSelection.selectRowList
          const selectedRowKeys = this.rowSelection.selectedRowKeys
          console.log(list, selectedRowKeys)
          if (!selected) {
            // 这里是取消勾选，删除对应的数组项
            selectedRowKeys.map((x, key) => {
              if (x === record.taskid) {
                selectedRowKeys.splice(key, 1)
              }
            })
            list.map((x, key) => {
              if (x.taskid === record.taskid) {
                list.splice(key, 1)
              }
            })
            console.log(this.rowSelection.selectedRowKeys)
          }
          if (selected) {
            // 这里是点击勾选，添加workerId字段到selectedRowKeys数组里
            this.rowSelection.selectedRowKeys.push(record.taskid)
            this.rowSelection.selectRowList.push(record)
            console.log(this.rowSelection.selectedRowKeys)
          }
        },
        // 全选
        onSelectAll: (selected, selectedRows, changeRows) => {
          console.log(selected, selectedRows, changeRows)
          if (selected) {
            changeRows.map(x => {
              this.rowSelection.selectedRowKeys.push(x.taskid)
              this.rowSelection.selectRowList.push(x)
            })
          }
          if (!selected) {
            const list = this.rowSelection.selectRowList
            const selectedRowKeys = this.rowSelection.selectedRowKeys
            changeRows.map((item, k) => {
              selectedRowKeys.map((x, key) => {
                if (x === item.taskid) {
                  selectedRowKeys.splice(key, 1)
                }
              })
              list.map((x, key) => {
                if (x.taskid === item.taskid) {
                  list.splice(key, 1)
                }
              })
            })
            this.rowSelection.selectRowList = list
            this.rowSelection.selectedRowKeys = selectedRowKeys
          }
        },
        selectedRowKeys: [],
        selectRowList: []
      },
      scroll: { x: 1000, y: 410 }
    }
  },
  components: {
    BusineUserTree: () => import('@/views/accept/BusineUserTree.vue'),
    CrcPersonModal: () => import('@/views/correction/condeploy/CrcPersonModal.vue'),
    AcceptHandleHeadComponent
  },
  created() {
    //console.log('this.$route.query.queryParam.queryList', this.$route.query.queryParam)

    try {
      //routeParam = JSON.parse(JSON.stringify(this.$route.query.queryParam))
      this.queryParam = { ...this.queryParam, ...this.$route.query.queryParam.TempqueryParam}
    } catch {
      console.log('路由传参非json格式')
    }
    this.headerChange()
    // 待处理人员
    this.initDefaultParam()
    this.queryUndoTaskList()
  },
  watch: {
    ucolumns: {
      handler(newValue, oldVal) {
        this.headerChange()
      },
      deep: true // 深度监听
    }
  },
  methods: {
    myEvent(e) {
      if (e) {
        this.scroll.y = this.scroll.y + e
      } else {
        this.scroll.y = 410
      }
    },
    headerChange() {
      console.log('移动后', this.ucolumns)
      this.header = {
        header: {
          cell: drag.methods.initDrag(this.ucolumns)
        }
      }
    },
    setColumns(columns) {
      console.log('重置前', this.ucolumns)
      // tableCountKey自增是为了让表格控件每次销毁强制更新
      this.tableCountKey += 1
      this.ucolumns = columns
      // this.ucolumns = columns
      console.log('重置后', this.ucolumns)
      this.setCardColumns()
    },
    /**
     * 显示处理界面
     */
    showHand(record, pattern) {
      console.log('record', record.taskid)
      record.TempqueryParam = this.queryParam
      this.$router.push({
        path: `/CorrectionCondeployEndOperation/${record.taskid}/${pattern}`,
        query: {
          url: '/CondeployDone',
          queryParam: record
        }
      })
    },
    onSearch(val) {
      this.queryParam.acceptcode = val
      this.queryParam.pageNumber = 1
      this.queryParam.pageSize = 20
      this.queryUndoTaskList()
    },

    // 接收时间监听判断开始结束日期是否合理
    startdateListen() {
      if (
        this.queryParam.startdate_01 > this.queryParam.startdate_02 &&
        this.queryParam.startdate_01 &&
        this.queryParam.startdate_02
      ) {
        this.queryParam.startdate_01 = undefined
      }
    },
    constartdateListen() {
      if (
        this.queryParam.constartdate > this.queryParam.consenddate &&
        this.queryParam.constartdate &&
        this.queryParam.consenddate
      ) {
        this.queryParam.constartdate = undefined
      }
    },
    /**
     * 初始化设置默认值
     */
    initDefaultParam() {
      this.queryParam.bizenum = this.Tp_biztype['correct'].value
      this.queryParam.userid = this.currentUser.userId
      this.queryParam.matid = '100000_360100-000201000000-CRC-001-01'
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery() {
      this.queryParam = {
        personname: '', // 社矫对象
        crime: '', // 罪名
        exeaddr: '', // 执行地
        concode: '', // 布控编号
        startdate_01: null, // 矫正开始时间
        startdate_02: null, // 矫正结束时间
        constartdate: null, // 布控开始时间
        consenddate: null, // 布控结束时间
        pageNumber: 1,
        pageSize: 20,
        order: 'desc',
        userid: '', // 用户id
        state: '1',
        bizenum: null,
        matid: null,
        statusapply: []
      }
      this.initDefaultParam()
      this.queryUndoTaskList()
    },
    tableChange(upagination, filters, sorter, { currentDataSource }) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryUndoTaskList()
    },
    tableChangeOther(upagination) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryUndoTaskList()
    },
    queryUndoTaskList() {
      this.queryList()
    },
    getCpQueryParam() {
      // 时间转换
      const cpQueryParam = JSON.parse(JSON.stringify(this.queryParam))
      if (this.queryParam.startdate_01?.format) {
        cpQueryParam.startdate_01 = this.queryParam.startdate_01.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.startdate_02?.format) {
        cpQueryParam.startdate_02 = this.queryParam.startdate_02.format('YYYY-MM-DD') + ' 23:59:59'
      }
      if (this.queryParam.constartdate?.format) {
        cpQueryParam.constartdate = this.queryParam.constartdate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.consenddate?.format) {
        cpQueryParam.consenddate = this.queryParam.consenddate.format('YYYY-MM-DD') + ' 23:59:59'
      }
      return cpQueryParam
    },

    queryList() {
      const queryParam = this.getCpQueryParam()
      if (queryParam.startdate_01 && queryParam.startdate_02) {
        queryParam.startdate = [queryParam.startdate_01, queryParam.startdate_02]
      }
      if (queryParam.constartdate && queryParam.consenddate) {
        queryParam.constartdate = [queryParam.constartdate, queryParam.consenddate]
      }
      this.loading = true
      queryMf_MyTaskDoneList(this.currentUser.userId, queryParam)
        .then(res => {
          console.log('表格数据:', res.data)
          if (res.code !== 0) {
            this.$message.error('获取数据失败')
          } else {
            this.listData = res.data.records
            // 将当前页码和数量与后台绑定
            this.upagination.total = res.data.total
            this.upagination.current = res.data.current
            this.upagination.pageSize = res.data.size
            this.needDealNum = res.data.total
          }
        })
        .catch(err => {
          this.listData = []
          console.log(err, '获取数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    rowClassName(record, index) {
      return index % 2 === 0 ? 'oddRow' : 'evenRow'
    },
    setCardColumns() {
      const columns = this.ucolumns.filter(child => child.key != 'index' && child.key != 'action')
      this.cardColumns = JSON.parse(JSON.stringify(columns))
    },
    crcTypeLabel(crcType) {
      if (this.Tp_crc_user[Number(crcType)]) {
        return this.Tp_crc_user[Number(crcType)].name
      }
      return ''
    },
    /**
     * 导出勾选人员照片
     */
    importPhotoZip() {
      const selectedRows = this.rowSelection.selectRowList
      if (selectedRows && selectedRows.length > 0) {
        const personIds = selectedRows
          .filter(el => el.perid != null && el.perid !== '' && el.perid !== undefined)
          .map(item => item.perid)
        if (personIds && personIds.length > 0) {
          downloadPersonPhoto(personIds)
            .then(res => {
              if (res.code && res.code != 0) {
                this.$message.error({
                  content: '材料下载失败',
                  key: 'fileDownload',
                  duration: 2
                })
              } else {
                downloadFile(res, '对象图片.zip')
                this.$message.success({
                  content: '材料下载成功',
                  key: 'fileDownload',
                  duration: 2
                })
              }
            })
            .catch(function (err) {
              console.log(err)
            })
        } else {
          this.$message.warning('当前勾选数据id为空')
        }
      } else {
        this.$message.warning('请勾选一条数据')
        return false
      }
    },
    /**
     * 导出社矫对象的word表单
     */
    importWord() {
      const selectedRows = this.rowSelection.selectRowList
      if (selectedRows && selectedRows.length > 0) {
        const personIds = selectedRows
          .filter(el => el.perid != null && el.perid !== '' && el.perid !== undefined)
          .map(item => item.perid)
        if (personIds && personIds.length > 0) {
          downloadPersonWord(personIds)
            .then(res => {
              if (res.code && res.code != 0) {
                this.$message.error({
                  content: '材料下载失败'
                })
              } else {
                const blob = new Blob([res], {
                  type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                })
                var url = window.URL.createObjectURL(blob)
                var a = document.createElement('a')
                a.href = url
                a.download = '资料名单.docx'
                a.click()
                this.$message.success({
                  content: '材料下载成功'
                })
              }
            })
            .catch(function (err) {
              console.log(err)
            })
        } else {
          this.$message.warning('当前勾选数据id为空')
        }
      } else {
        this.$message.warning('请勾选一条数据')
        return false
      }
    },
    showPersonInfo(record) {
      this.$refs.crcPersonModalRef.init(record.perid)
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/components/TableDrag/style.less';
</style>

<style lang="scss" scoped>
@import '~@/assets/css/apply/breathingLamp.scss';

.cursor_pointer:hover {
  color: #55a7f5;
}

.accept_content {
  &_table {
    &_font_red {
      color: #ca0000;
      font-size: 16px;
      font-family: 'PingFang-SC-Heavy';
      font-weight: 400;
    }

    ::v-deep .ant-table-row-cell-break-word {
      font-size: 16px;
      font-family: 'PingFang-SC-Heavy';
      font-weight: 400;
      color: #2c2c2c;
    }

    ::v-deep .ant-table-thead>tr>th {
      height: 50px;
    }

    ::v-deep .ant-table-row-cell-break-word {
      font-size: 16px;
      font-family: 'PingFang-SC-Heavy';
      font-weight: 600;
      color: #2c2c2c;
    }

    // ::v-deep .ant-pagination-total-text {
    //   font-size: 16px;
    //   font-family: 'PingFang-SC-Heavy';
    //   font-weight: 400;
    //   color: #8e97b9;
    // }

    ::v-deep .ant-table-body,
    .ant-table-header {
      word-break: break-all;

      &::-webkit-scrollbar {
        width: 10px;
        /*高宽分别对应横竖滚动条的尺寸*/
        // height: 10px;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: #a2c6e1;
      }

      &::-webkit-scrollbar-track {
        // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        border-radius: 5px;
        background: transparent;
      }
    }
  }
}
</style>
